import { Client, Room } from "colyseus";
import { Schema, type, MapSchema } from "@colyseus/schema";

export class Player extends Schema {
  @type("string") color: string = "";
  @type("number") x: number = 0;
  @type("number") y: number = 0;
  @type("number") z: number = 0;
}

export class State extends Schema {
  @type({ map: Player }) players = new MapSchema<Player>();
}

export class GameRoom extends Room<State> {

  public onCreate(options: any): void | Promise<any> {
    this.state = new State();

    this.onMessage("move", (client, data) => {
      const player = this.state.players.get(client.sessionId);
      // console.log('server move', client.sessionId)
      if (!player) return;
      player.x = data.x;
      player.y = data.y;
      player.z = data.z;
      this.broadcast('player-moved', { sessionId: client.sessionId, x: player.x, y: player.y, z: player.z }, { except: client });
    });
  }

  public onJoin(client: Client<any, any>, options?: any, auth?: any): void | Promise<any> {
    const player = new Player();
    player.color = options.color;
    player.x = options.x;
    player.y = options.y;
    player.z = options.z;
    this.state.players.set(client.sessionId, player);
    
    console.log('server', 'joined', client.sessionId, options)
    this.broadcast('player-joined', {
      sessionId: client.sessionId,
      player: { x: player.x, y: player.y, z: player.z, color: player.color }
    });
    client.send("room-state", {
      players: Array.from(this.state.players.entries()),
    });
  }

  public onLeave(client: Client<any, any>, consented?: boolean): void | Promise<any> {
    this.broadcast('player-left', { sessionId: client.sessionId });

    this.state.players.delete(client.sessionId);
  }

  public onDispose(): void | Promise<any> {
    console.log("Room disposed");
  }

}